<template>
  <el-card shadow="always" :body-style="{ padding: '20px' }">
    <el-form :inline="true" size="small" :model="searchObj">
      <el-form-item label="">
        <el-input v-model="searchObj.username"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          @click="getUserInfoList()"
          >搜索</el-button
        >
        <el-button @click="resetSearch">清空</el-button>
      </el-form-item>
    </el-form>
    <el-button
      type="primary"
      size="small"
      style="margin-right: 10px"
      @click="addUser"
      >添加</el-button
    >
    <el-popconfirm
      confirm-button-text="确定"
      cancel-button-text="取消"
      icon="el-icon-info"
      icon-color="red"
      title="确定删除选中的用户吗?"
      @confirm="removeUsers"
    >
      <el-button size="small" type="danger" slot="reference" :disabled='removeIds.length==0'
        >批量删除</el-button
      >
    </el-popconfirm>

    <el-table
      border
      stripe
      style="margin: 20px 0"
      :data="userInfoList"
      v-loading="loading"
      element-loading-text="拼命加载中"
      element-loading-spinner="el-icon-loading"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        type="selection"
        width="55"
        align="center"
      ></el-table-column>
      <el-table-column type="index" label="序号" width="55" align="center">
      </el-table-column>
      <el-table-column
        label="用户名"
        width="100"
        prop="username"
      ></el-table-column>
      <el-table-column label="用户昵称" prop="nickName"></el-table-column>
      <el-table-column
        label="角色列表"
        width="200"
        prop="roleName"
      ></el-table-column>
      <el-table-column
        label="创建时间"
        width="200"
        prop="gmtCreate"
      ></el-table-column>
      <el-table-column
        label="更新时间"
        width="200"
        prop="gmtModified"
      ></el-table-column>
      <el-table-column label="操作" width="200">
        <template slot-scope="row">
          <el-button
            size="mini"
            type="info"
            icon="el-icon-user-solid"
            title="设置角色"
            v-if="$hasBP('btn.User.assgin')"
            @click="setUser(row)"
          ></el-button>
          <el-button
            size="mini"
            type="primary"
            icon="el-icon-edit-outline"
            title="修改用户"
            v-if="$hasBP('btn.User.update')"
            @click="updateUser(row)"
            style="margin-right: 10px"
          ></el-button>
          <el-popconfirm
            confirm-button-text="确定"
            cancel-button-text="不用了"
            icon="el-icon-info"
            icon-color="red"
            title="确定删除此用户吗？"
            @confirm="removeUser(row)"
          >
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete-solid"
              title="删除用户"
              v-if="$hasBP('btn.User.remove')"
              slot="reference"
            ></el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      @size-change="handleSizeChange"
      @current-change="getUserInfoList"
      :current-page="currentPage"
      :page-sizes="[3, 5, 7, 9]"
      :page-size="pageSize"
      layout=" prev, pager, next, jumper,->, sizes,total"
      :total="total"
    />
    <el-dialog
      :title="adduserdata.id ? '修改用户' : '添加用户'"
      :visible.sync="dialogUserVisible"
      top="0"
      @closed="cancle"
    >
      <el-form
        label-width="120px"
        :rules="rules"
        :model="adduserdata"
        ref="userFrom"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="adduserdata.username"
            placeholder="请输入用户名"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户昵称" prop="userNickName">
          <el-input
            v-model="adduserdata.nickName"
            placeholder="请输入用户昵称"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!adduserdata.id">
          <el-input
            v-model="adduserdata.password"
            placeholder="请输入密码"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            size="small"
            style="float: right; transform: translateX(10px)"
            @click="addOrUpdateUser"
            >确认</el-button
          >
          <el-button size="small" style="float: right" @click="cancle"
            >取消</el-button
          >
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog
      title="设置角色"
      :visible.sync="showSetUser"
      top="0"
      @closed="cancleUserSet"
    >
      <el-form label-width="80px">
        <el-form-item label="用户名">
          <el-input v-model="setUserName" disabled></el-input>
        </el-form-item>
        <el-form-item label="角色列表">
          <el-checkbox @change="changeCheck" v-model="checkAllrole">
            全部
          </el-checkbox>
          <el-checkbox-group v-model="clickRoleList" @change="checkboxHandle">
            <el-checkbox
              :label="item.id"
              v-for="item in roleList"
              :key="item.id"
            >
              {{ item.roleName }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label-width="80%" size="normal">
          <el-button size="small" @click="cancleUserSet">取消</el-button>
          <el-button type="primary" size="small" @click="reqSetUser"
            >确认</el-button
          >
        </el-form-item>
      </el-form>
    </el-dialog>
  </el-card>
</template>

<script>
import { cloneDeep } from "lodash";
export default {
  name: "UserList",
  data() {
    return {
      searchObj: {
        username: "",
      },
      currentPage: 1,
      pageSize: 5,
      total: 0,
      userInfoList: [],
      loading: false,
      dialogUserVisible: false,
      adduserdata: {},
      rules: {
        username: [
          { required: true, message: "用户名不能为空" },
          { min: 4, message: "用户名不能小于4位" },
        ],
        password: [{ validator: this.validatePass, trigger: "blur" }],
      },
      showSetUser: false,
      setUserName: "",
      roleList: [], //所有的角色列表
      clickRoleList: [], //选中的角色id列表
      userId: "", //修改的那个用户的id
      checkAllrole: false,
      removeIds: [],
    };
  },
  mounted() {
    this.getUserInfoList();
  },
  methods: {
    //改变每页显示个数
    handleSizeChange(pageSize) {
      this.pageSize = pageSize;
      this.getUserInfoList();
    },
    //表单正则验证
    validatePass(rule, value, callback) {
      //最后一定要写callback
      let reg = /^[a-zA-Z0-9]{6,16}$/;
      if (value == "") {
        callback(new Error("密码不能为空"));
      }
      if (!value || value.length < 6) {
        callback(new Error("请输入6位以上密码"));
      }
      if (!reg.test(value)) {
        callback(new Error("请输入6-16位包含数字以及字母密码"));
      }
      callback();
    },
    //获取用户信息列表
    async getUserInfoList(currentPage = 1) {
      this.currentPage = currentPage;
      const { pageSize, searchObj } = this;
      this.loading = true;
      let res = await this.$API.user.getPageList(
        this.currentPage,
        pageSize,
        searchObj
      );
      this.userInfoList = res.data.items;
      this.total = res.data.total;
      this.loading = false;
    },
    //清空搜索框按钮
    resetSearch() {
      this.searchObj = { username: "" };
      this.getUserInfoList();
    },
    //点击添加用户回调
    addUser(row) {
      this.dialogUserVisible = true;
    },
    //添加或修改user回调
    async addOrUpdateUser() {
      const { adduserdata } = this;

      this.$refs.userFrom.validate((valid) => {
        if (valid) {
          this.loading = true;
          this.$API.user[adduserdata.id ? "update" : "add"](adduserdata).then(
            (result) => {
              this.getUserInfoList(
                this.currentPage == 1 ? 1 : this.currentPage
              );
              this.$message({
                type: "success",
                message: adduserdata.id ? "修改成功" : "添加成功",
              });
              this.adduserdata = {};
              this.loading = false;
              this.dialogUserVisible = false;
            }
          );
        } else {
          this.$message({
            type: "error",
            message: "请输入正确的用户名或密码",
          });
        }
      });
    },
    //取消按钮回调
    cancle() {
      this.$refs.userFrom.resetFields();
      this.dialogUserVisible = false;
      this.adduserdata = {};
    },
    //设置角色按钮回调
    async setUser(row) {
      this.userId = row.row.id;
      let res = await this.$API.user.getRoles(row.row.id);
      this.roleList = res.data.allRolesList;
      this.setUserName = row.row.username;
      this.showSetUser = true;
      res.data.assignRoles.forEach((item) => {
        this.clickRoleList.push(item.id);
      });
      this.checkAllrole = this.clickRoleList.length === this.roleList.length;
    },
    //点击全选框
    changeCheck(event) {
      if (event) {
        this.checkAllrole = true;
        this.clickRoleList = [];
        this.roleList.forEach((item) => {
          this.clickRoleList.push(item.id);
        });
      } else {
        this.clickRoleList = [];
        this.checkAllrole = false;
      }
    },
    checkboxHandle() {
      this.checkAllrole = this.clickRoleList.length === this.roleList.length;
    },
    //设置角色弹出框取消按钮回调
    cancleUserSet() {
      this.showSetUser = false;
      this.clickRoleList = [];
      this.userId = "";
    },
    //设置角色回调
    async reqSetUser() {
      let { userId } = this;
      let roles = this.clickRoleList.join(",");
      let res = await this.$API.user.assignRoles(userId, roles);
      this.cancleUserSet();
      this.getUserInfoList(this.currentPage);
    },
    //修改用户回调
    updateUser(row) {
      this.dialogUserVisible = true;
      this.adduserdata = cloneDeep(row.row);
    },
    //删除按钮回调
    async removeUser(row) {
      const { id } = row.row;
      await this.$API.user.removeById(id);
      this.$message({ type: "success", message: "删除成功" });
      this.getUserInfoList(
        this.userInfoList.length ? this.currentPage : this.currentPage - 1
      );
    },
    handleSelectionChange(row) {
      this.removeIds = row.map((item) => item.id);
    },
    //批量删除按钮回调
    async removeUsers() {
      try {
        await this.$API.user.removeUsers(this.removeIds);
        this.$message.success("删除成功");
        this.getUserInfoList();
      } catch (error) {
        this.$message({ type: "error", message: error.message });
      }
    },
  },
};
</script>

<style lang="scss" scoped>
</style>